package com.bizmda.bizsip.config;

import cn.hutool.core.io.resource.ClassPathResource;
import com.bizmda.bizsip.common.BizException;
import com.bizmda.bizsip.common.BizResultEnum;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.yaml.snakeyaml.Yaml;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 史正烨
 */
@Slf4j
@Getter
public class SourceConfigMapping {
    private final Map<String, CommonSourceConfig> sourceConfigMap;
    private final String configPath;

    public SourceConfigMapping(String configPath) throws BizException{
        this.configPath = configPath;
        Yaml yaml = new Yaml();
        List<Map<String,Object>> sourceMapList;
        try {
            if (this.configPath == null) {
                log.info("application.yml中没有配置bizsip.config-path，从ClassPath资源中读取source.yml");
                ClassPathResource resource = new ClassPathResource("/source.yml");
                sourceMapList = yaml.load(new FileInputStream(resource.getFile()));
            }
            else {
                log.info("从{}中读取source.yml",configPath);
                sourceMapList = yaml.load(new FileInputStream(configPath + "/source.yml"));
            }
        } catch (FileNotFoundException e) {
            log.error("source.yml不存在，Source配置加载失败!");
            throw new BizException(BizResultEnum.SOURCE_FILE_NOTFOUND,e);
        }
        if (sourceMapList == null) {
            sourceMapList = new ArrayList<>();
        }
        CommonSourceConfig sourceConfig;
        this.sourceConfigMap = new HashMap<>();
        for (Map<String,Object> sourceMap:sourceMapList) {
            sourceConfig = new CommonSourceConfig(sourceMap);
            this.sourceConfigMap.put(sourceConfig.getId(),sourceConfig);
        }
    }

    public CommonSourceConfig getSourceId(String id) {
        return this.sourceConfigMap.get(id);
    }
}
